<?php



include_once '../core/core.php';

if(!isset($_GET['id'])){
		exit('链接错误！');
	}

	$id = $_GET['id'];

	$sql = "select * from project where id=".$id;

	$res = $db->find($sql);
	if(!$res){
		exit('数据库未找到，或已被删除！');
	}

	$data = $res[0];
	$sql = "select * from fields where pid=".$data['id'];

	$fields = $db->find($sql);
	
	
	
	if(!$fields){
		err('请先创建爬取字段！');
	}
	
	$sql = "select * from dbconfig where id=".$data['dbid'];

	$database = $db->find($sql);
	
	if(!$database){
		err('请先选择导入数据库！');
	}
	
	if(!$data['target']){
		err('请先选择导入表！');
	}
	
	
	if($data['method']=='GET'){
		$res = curl_get_request($data['url']);
	}else{
		$res = curl_post_request($data['url']);
	}
	if(!$res){
		err('数据无法抓取!');
	}
	
	$result = [];
	$field_str = '';
    foreach($fields as $v){
	   $newfieldsdata = getFieldData($res,$v['param']);
	   if($field_str==''){
		   $field_str .=' `'.$v['field'].'` ';
	   }else{
		   $field_str .=' ,`'.$v['field'].'` ';
	   }
	   if(is_array($newfieldsdata)){
		   foreach($newfieldsdata as $kk=>$vv){
			   $result[$kk][$v['field']] = "'".$vv."'";
		   }
		   
	   }
	   
	   
    }
	
	


	//var_dump($result);
	
	//引入配置数据库
	include_once '../core/db.class.php';
	$database = $database[0];
	$config = [
		'host'=>$database['host'],
		'port'=>$database['host'],
		'dbname'=>$database['dbname'],
		'user'=>$database['user'],
		'pass'=>$database['pass'],
	];
	$newdb = new db($config);
	
	/**
	
	[
		'title'=>[
			'xx','abc'
		],
		'litpic'=>[
			'aaa','bbb'
		]
	]
	
		[
			['title'=>xx,'litpic'=>xxx],
			['title'=>xx,'litpic'=>xxx],
			['title'=>xx,'litpic'=>xxx],
			['title'=>xx,'litpic'=>xxx],
		]
	
	*/
	
	$sql = '';
	foreach($result as $v){
		
		$value = implode(',',$v);
		$sql .= " INSERT INTO `".$data['target']."`(".$field_str.") VALUES (".$value.");";
		
	}
	$res = $newdb->add($sql);
	
	if($res){
		success('导入成功！',get_host().'/index.html');
	}else{
		err('数据导入表失败！');
	}
	
	
	
	






